﻿using Dapper_Core.Basic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;

namespace Dapper_Core.Basic
{
    public class BaseModel
    {
        private bool hasAdded = false;
        private ArrayList dynamicPropertyKeys = new ArrayList(32);
        private ArrayList dynamicPropertyValues = new ArrayList(32);
        private Dictionary<string, object> tempDict = new Dictionary<string, object>();

        private bool enableHasChanged = true;
        /// <summary>
        /// 为真时，HasChanged方法检查字段值是否有变化。否则认为字段值已变化，直接返回true
        /// </summary>
        [Editable(false)]
        public bool EnableHasChanged 
        {
            get { return enableHasChanged; }
            set { enableHasChanged = value; }
        }
        private bool recordChange = true;
        /// <summary>
        /// 是否记录属性值的变化
        /// </summary>
        [Editable(false)]
        public bool RecordChange
        {
            get { return recordChange; }
            set
            {
                if (!value)
                {
                    changedProperty.Clear();
                }
                recordChange = value;
            }
        }
        private ArrayList changedProperty = new ArrayList(32);
        /// <summary>
        /// 设置过的状态变化字典
        /// </summary>
        [Editable(false)]
        public ArrayList ChangedProperty
        {
            get { return changedProperty; }
            set { changedProperty = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="propertyName"></param>
        public void ToChanged(string propertyName)
        {
            if (recordChange)
            {
                //updateInnerTs();
                string s = propertyName.ToLower();
                if (CaseSensitive) s = propertyName;
                if (changedProperty.Contains(s))
                    return;
                changedProperty.Add(s);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="oldvalue"></param>
        /// <param name="newValue"></param>
        public void ToChanged(string propertyName, object oldvalue, object newValue)
        {

            if (HasChanged(propertyName, oldvalue, newValue))
            {
                //updateInnerTs();
                string s = propertyName.ToLower();
                if (CaseSensitive) s = propertyName;
                if (changedProperty.Contains(s))
                    return;
                changedProperty.Add(s);
            }
        }
        /// <summary>
        /// 与原有值判断是否发生变化
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="oldValue"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool HasChanged(string propertyName, object oldValue, object value)
        {
            if (recordChange)
            {
                if (!enableHasChanged) return true;
                if (oldValue == null && value == null) return false;
                if (oldValue != null)
                {
                    Type t = oldValue.GetType();
                    if (t.IsValueType)
                    {
                        if (Activator.CreateInstance(t).Equals(oldValue)) return true;
                    }
                    return !oldValue.Equals(value);
                }
                if (value != null) return !value.Equals(oldValue);
            }
            return false;
        }

        /// <summary>
        /// 是否删除（0未删除、1已删除）
        /// </summary>
        public int IsDeleted { get; set; }
        /// <summary>
        /// 创建人
        /// </summary>
        public string Creator { get; set; }
        private DateTime createDate = DateTime.Now;
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateDate
        {
            get { return this.createDate; }
            set { this.createDate = value; }
        }
        /// <summary>
        /// 修改人
        /// </summary>
        public string Modifier { get; set; }
        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime? ModifyDate { get; set; }
        /// <summary>
        /// 删除人
        /// </summary>
        public string Deleter { get; set; }
        /// <summary>
        /// 删除时间
        /// </summary>
        public DateTime? DeleteDate { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remarks { get; set; }
        /// <summary>
        /// 动态属性的键
        /// </summary>
        [Editable(false)]
        public ArrayList DynamicPropertyKeys
        {
            get { return dynamicPropertyKeys; }
            set { dynamicPropertyKeys = value; }
        }
        /// <summary>
        /// 动态属性的值
        /// </summary>
        [Editable(false)]
        public ArrayList DynamicPropertyValues
        {
            get { return dynamicPropertyValues; }
            set { dynamicPropertyValues = value; }
        }

        private bool caseSensitive = false;
        /// <summary>
        /// setFieldValue的动态属性是否大小写敏感，默认为false
        /// </summary>
        [Editable(false)]
        public bool CaseSensitive
        {
            get { return caseSensitive; }
            set { caseSensitive = value; }
        }

        private bool recordDynamicNullValue = false;
        /// <summary>
        /// 是否记录动态属性的null值，默认不记录
        /// </summary>
        [Editable(false)]
        public bool RecordDynamicNullValue
        {
            get { return recordDynamicNullValue; }
            set { recordDynamicNullValue = value; }
        }

        /// <summary>
        /// 获取字段的值,不区分fieldName的大小写
        /// 支持多级搜索：将fieldName按'.'分隔，一级一级往下找，任何一级找不到会返回null（根据fieldName先查属性再查动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public object GetFieldValue(string fieldName)
        {
            string[] fieldNames = fieldName.Split('.');
            object currentFieldValue = this;
            BaseModel currentDto = null;

            for (int i = 0; i < fieldNames.Length; i++)
            {
                if (currentFieldValue == null)
                    return null;
                currentDto = currentFieldValue as BaseModel;
                if (currentDto == null)
                    return null;

                fieldName = fieldNames[i];
                currentFieldValue = GetFieldValue(fieldName, currentDto);
            }
            return currentFieldValue;
        }
        /// <summary>
        /// 获取字段的值,不区分fieldName的大小写（根据fieldName先查属性再查动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        private object GetFieldValue(string fieldName, BaseModel dto)
        {
            PropertyInfo pi = null;
            try
            {
                pi = dto.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception ex)
            {
                if (ex is System.Reflection.AmbiguousMatchException)
                {
                    //解决父类与子类中有相同字段名称的问题
                    pi = dto.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                }
                else
                {
                    throw ex;
                }
            }
            if (pi != null)
            {
                return pi.GetValue(dto, null);
            }

            string s = fieldName.ToLower();
            if (CaseSensitive) s = fieldName;
            if (dto.DynamicPropertyKeys.Contains(s))
            {
                int index = dto.DynamicPropertyKeys.IndexOf(s);
                return dto.DynamicPropertyValues[index];
            }

            return null;
        }

        /// <summary>
        /// 获取动态字段的值,不区分fieldName的大小写（仅查询动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public object GetDynamicFieldValue(string fieldName)
        {
            string s = fieldName.ToLower();
            if (this.CaseSensitive) s = fieldName;
            if (dynamicPropertyKeys.Contains(s))
            {
                int index = dynamicPropertyKeys.IndexOf(s);
                return dynamicPropertyValues[index];
            }

            return null;
        }

        /// <summary>
        /// 设置字段的值,不区分fieldName的大小写（根据fieldName先查属性再查动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public void SetFieldValue(string fieldName, object value)
        {
            try
            {
                /*
                PropertyInfo[] pis = this.GetType().GetProperties();
                bool setted = false;
                for (int i = 0; i < pis.Length; i++)
                {
                    if (pis[i].Name.ToLower() == s)
                    {
                        pis[i].SetValue(this, Util.GetVOPropertyValueByType(pis[i].PropertyType, fieldName, value), null);
                        setted = true;
                        break;
                    }
                }*/
                PropertyInfo pi = null;
                try
                {
                    pi = this.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                }
                catch (Exception ex)
                {
                    if (ex is System.Reflection.AmbiguousMatchException)
                    {
                        //解决父类与子类中有相同字段名称的问题
                        pi = this.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                    }
                    else
                    {
                        throw ex;
                    }
                }

                if (pi != null)
                {
                    try
                    {
                        pi.SetValue(this, Util.GetVOPropertyValueByType(pi.PropertyType, fieldName, value), null);
                    }
                    catch
                    {
                        //pi为只读属性时，抛异常.如ProjectDTO.ProjectClass.
                    }
                }
                else
                {
                    SetDynamicFieldValue(fieldName, value);
                }

            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 设置动态字段的值,不区分fieldName的大小写（仅查询动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public void SetDynamicFieldValue(string fieldName, object value)
        {
            string s = fieldName.ToLower();
            if (CaseSensitive) s = fieldName;

            if ((s == "recorddynamicnullvalue") && (value.ToString().ToLower() == "true"))
            {
                recordDynamicNullValue = true;
            }

            int index = this.dynamicPropertyKeys.IndexOf(s);
            if (index > -1)
            {
                if (dynamicPropertyValues.Count > index)
                    dynamicPropertyValues[index] = value;
            }
            else
            {
                //自定义字段也需要保留空
                if (value != null || (recordDynamicNullValue == true && hasAdded == true) || s.Contains("userdef") || s.Contains("freeitem"))
                {
                    dynamicPropertyKeys.Add(s);
                    dynamicPropertyValues.Add(value);
                }
                else if (hasAdded == false)
                {
                    if (!tempDict.ContainsKey(s))
                        tempDict.Add(s, value);
                }
            }

            if (hasAdded == false && recordDynamicNullValue == true)
            {
                hasAdded = true;
                foreach (KeyValuePair<string, object> ent in tempDict)
                {
                    int idex = dynamicPropertyKeys.IndexOf(ent.Key);
                    if (index > -1)
                    {
                        dynamicPropertyValues[idex] = ent.Value;
                    }
                    else
                    {
                        dynamicPropertyKeys.Add(ent.Key);
                        dynamicPropertyValues.Add(ent.Value);
                    }
                }
            }
        }

        /// <summary>
        /// 移除动态字段的值,不区分fieldName的大小写（仅移除动态属性）
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public void RemoveDynamicFieldValue(string fieldName)
        {
            string s = fieldName.ToLower();
            if (this.CaseSensitive) s = fieldName;
            int index = -1;
            if (dynamicPropertyKeys.Contains(s))
            {
                index = dynamicPropertyKeys.IndexOf(s);
                dynamicPropertyKeys.RemoveAt(index);
                dynamicPropertyValues.RemoveAt(index);
            }
        }

        /// <summary>
        /// 深层复制对象
        /// </summary>
        /// <returns></returns>
        public virtual object Clone()
        {
            BaseModel d = (BaseModel)DataCloner.Clone(this);
            return d;
        }
    }
}
